package com.courage.crawler.boss.service.crawler;

import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class PageCrawlerRule implements CrawlerRule {

    @Override
    public void doAction(ChromeDriverContext chromeDriverContext) throws InterruptedException {
        log.info("进入分页页码爬虫");
        ChromeDriver driver = chromeDriverContext.getChromeDriver();
        // 下拉到底部
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, 4500)");
        List<WebElement> pageLinks = driver.findElementsByCssSelector(".options-pages a");
        int selectCursor = 0;
        for (int i = 0; i < pageLinks.size(); i++) {
            WebElement webElement = pageLinks.get(i);
            String className = webElement.getAttribute("class");
            if ("selected".equals(className)) {
                log.info("当前页码 pageNum:" + webElement.getText());
                selectCursor = i;
            }
        }

        try {
            //判断是否有浮窗 div login-dialog-wrapper span:icon-close
            WebElement loginDiv = driver.findElement(new By.ByClassName(("login-dialog-wrapper")));
            if (loginDiv != null) {
                log.info("关闭login登录窗口");
                WebElement closeSpan = driver.findElement(new By.ByClassName(("icon-close")));
                closeSpan.click();
            }
        } catch (Exception e) {
            log.error("login div error:", e);
        }

        //判断是否有下一页
        if (pageLinks.size() > selectCursor + 1) {
            WebElement nextLink = pageLinks.get(selectCursor + 1);
            nextLink.click();
            Thread.sleep(3000);
        } else {
            chromeDriverContext.setPageEnd(true);
        }
    }

}
